package com.song.sparkstudy.stream;

import java.util.Arrays;

import org.apache.spark.SparkConf;
import org.apache.spark.api.java.StorageLevels;
import org.apache.spark.api.java.function.FlatMapFunction;
import org.apache.spark.api.java.function.Function2;
import org.apache.spark.api.java.function.PairFunction;
import org.apache.spark.storage.StorageLevel;
import org.apache.spark.streaming.Durations;
import org.apache.spark.streaming.api.java.JavaDStream;
import org.apache.spark.streaming.api.java.JavaPairDStream;
import org.apache.spark.streaming.api.java.JavaReceiverInputDStream;
import org.apache.spark.streaming.api.java.JavaStreamingContext;

import scala.Tuple2;

public class JavaNetWordCount {
	
	
	public static void main(String[] args) {
		
		SparkConf conf = new SparkConf().setAppName("net work cout");
		
		JavaStreamingContext context =  new JavaStreamingContext(conf ,Durations.seconds(20));
		
		JavaReceiverInputDStream<String> lines = context.socketTextStream("localhost", 8888,StorageLevels.MEMORY_AND_DISK);
		
		JavaDStream<String> words   = lines.flatMap(new FlatMapFunction<String, String>() {

			@Override
			public Iterable<String> call(String str) throws Exception {
				// TODO Auto-generated method stub
				return Arrays.asList( str.split(" "));
			}
			
		});
		
		JavaPairDStream<String, Integer> wordcounts = words.mapToPair( new PairFunction<String, String, Integer>() {

			@Override
			public Tuple2<String, Integer> call(String key) throws Exception {
				// TODO Auto-generated method stub
				return new Tuple2<String, Integer>(key, 1);
			}
		} ).reduceByKey(new Function2<Integer, Integer, Integer>() {
			
			@Override
			public Integer call(Integer v1, Integer v2) throws Exception {
				// TODO Auto-generated method stub
				return v1+ v2;
			}
		});
		
		wordcounts.print();
		context.start();
		context.awaitTermination();
		
	}
}
